# import sys
# sys.path.append('E:\\gitee\\mp_alwaysup_fastapi')

from typing import List, Dict, Any
from process import baseFunction as bf


def CloseData_HS_MARKET(tradeDate: str, ts_code: str) -> List[Dict[str, Any]]:
    market_amount_data = HS_MARKET_DAILY_DATA(tradeDate, ts_code)
    # print(market_amount_data)
    return market_amount_data

def HS_MARKET_DAILY_DATA(tradeDate: str, ts_code: str):
    level1_result = level1(tradeDate, ts_code)

    level2_result = level2(tradeDate, ts_code)
    
    level3_result = level3(tradeDate, ts_code)

    if isinstance(level1_result, tuple):
        level1_result = list(level1_result)
    if isinstance(level2_result, tuple):
        level2_result = list(level2_result)
    if isinstance(level3_result, tuple):
        level2_result = list(level3_result)
        
    result_list = level1_result + level2_result + level3_result
    return result_list

def Market_amount(tradeDate: str, ts_code: str) -> List[Dict[str, Any]]:
    # ts_code = 'HS_MARKET'
    table_name = 'market_amount'
    # 定义表的字段名列表
    field_names = ["amount", "amount_chg", "float_mv", "float_mv_chg"]
    conditions = {"ts_code": ts_code, "trade_date": tradeDate}
    query_txt = bf.generate_query(table_name=table_name,
                                  field_names=field_names,
                                  conditions=conditions)
    result = bf.execute_query(query_txt, tuple(conditions.values()))
    return result if result else []


def Basic_mv_count(conditions) -> List[any]:
    # 定义表的字段名列表
    field_names = ["trade_date", "total_stocks", "mv_5y", "mv_5y_30y", "mv_30y_1by", "mv_1by_5by", "mv_5by_1ky",
                   "mv_1ky_5ky", "mv_5ky_1wy", "mv_1wy_2wy", "mv_above2wy", "mvTop100Sum",  "mvTop100SumPercent"]
    table_name = 'daily_basic_mv_count'
    orderBy = 'trade_date'
    query_txt = bf.generate_query(table_name=table_name,
                                  field_names=field_names,
                                  conditions=conditions,
                                  order_by=orderBy)
    result_data = bf.execute_query(query_txt, tuple(conditions.values()))
    return result_data


def Turnover_statistics(conditions) -> List[any]:
    # 定义表的字段名列表
    field_names = ["trade_date", "ts_code", "turnover_1pct", "turnover_1_5pct", "turnover_5_10pct", "turnover_above_10pct", "turnoverAbove5PctRatio", "turnoverAbove5_mvChg"]
    table_name = 'daily_turnover_statistics'
    orderBy = 'trade_date'
    query_txt = bf.generate_query(table_name=table_name,
                                  field_names=field_names,
                                  conditions=conditions,
                                  order_by=orderBy)
    result_data = bf.execute_query(query_txt, tuple(conditions.values()))
    return result_data


def level1(tradeDate: str, ts_code: str) -> List[Dict[str, Any]]:
    result = Market_amount(tradeDate, ts_code)
    if not result:
        return [], 0.0

    queryData = result[0] if len(result) > 0 else None
    data = {
        'ts_code': 'HS_MARKET',
        'trade_date': tradeDate,
        'ts_name': 'A股市场',
        'level': 1,
    }

    if queryData:
        sum_mv = round(queryData.get('float_mv', 0) / 10000, 2)
        result_data = [
            { **data, 'title': '成交金额', 'value': queryData.get('amount', 0), 'unit': '亿元',},
            { **data, 'title': '成交变化', 'value': queryData.get('amount_chg', 0), 'unit': '亿元', },
            { **data, 'title': '流通市值', 'value': sum_mv, 'unit': '万亿',},
            { **data, 'title': '市值变化', 'value': round(queryData.get('float_mv_chg', 0), 0), 'unit': '亿元',}
        ]
    else:
        result_data = []
    return result_data


def level2(tradeDate: str, ts_code: str) -> List[Dict[str, Any]]:
    result_data = []
    conditions = {"trade_date": tradeDate}
    result = Basic_mv_count(conditions)
    # # 假设只返回一条记录，直接取第一条记录
    if not result:
        return result_data
    queryData = result[0]
    # 初始化基础数据
    data = {
        'ts_code': 'MV_COUNT',
        'trade_date': tradeDate,
        'ts_name': '流通市值分段数量',
        'level':  2,
        'unit': '只',
    }

    # 处理查询结果    
    if queryData:
        result_data = [
            {
                **data,
                'field': 'mv_5y',
                'title': '[0,5]亿',                
                'value': queryData.get('mv_5y', 0),
            },
            {
                **data,
                'field': 'mv_1ky_5ky',
                'title': '[1K,5K]亿',
                'value': queryData.get('mv_1ky_5ky', 0),
            },
            {
                **data,
                'field': 'mv_5ky_1wy',
                'title': '[5K,10K]亿',
                'value': queryData.get('mv_5ky_1wy', 0),
            },
            {
                **data,
                'field': 'mv_1wy_2wy',
                'title': '[10K,20K]亿',
                'value': queryData.get('mv_1wy_2wy', 0),
            },
            {
                **data,
                'field': 'mv_above2wy',
                'title': '[20K,∞]亿',
                'value': queryData.get('mv_above2wy', 0),
            },
            {
                **data,
                'field': 'above1kySum',
                'title': '1千亿以上总数',
                'value': queryData.get('mv_1ky_5ky', 0) + queryData.get('mv_5ky_1wy', 0)+queryData.get('mv_1wy_2wy', 0) + queryData.get('mv_above2wy', 0),
            },
            {
                **data,
                'field': 'mvTop100Sum',
                'title': '前百总市值',
                'value': queryData.get('mvTop100Sum', 0),
                'unit': '万亿'
            },
            {
                **data,
                'field': 'mvTop100SumPercent',
                'title': '前百总市值占比',
                'value': queryData.get('mvTop100SumPercent', 0),
                'unit': '%'
            },    
        ]
    return result_data

def level3(tradeDate: str, ts_code: str) -> List[Dict[str, Any]]:
    result_data = []
    conditions = {"ts_code": ts_code, "trade_date": tradeDate}
    result = Turnover_statistics(conditions)
    # # 假设只返回一条记录，直接取第一条记录
    if not result:
        return result_data
    queryData = result[0]
    # 初始化基础数据
    data = {
        'ts_code': 'TURNOVER_COUNT',
        'trade_date': tradeDate,
        'ts_name': '换手率分段数量',
        'level':  3,
        'unit': '只',
    }

    # 处理查询结果    
    if queryData:
        result_data = [
            {
                **data,
                'field': 'turnover_1pct',
                'title': '小于1%',                
                'value': queryData.get('turnover_1pct', 0),
            },
            {
                **data,
                'field': 'turnover_1_5pct',
                'title': '[1%,5%]',
                'value': queryData.get('turnover_1_5pct', 0),
            },
            {
                **data,
                'field': 'turnover_5_10pct',
                'title': '[5%,10%]',
                'value': queryData.get('turnover_5_10pct', 0),
            },
            {
                **data,
                'field': 'turnover_above_10pct',
                'title': '大于10%',
                'value': queryData.get('turnover_above_10pct', 0),
            },
            {
                **data,
                'field': 'turnoverAbove5PctRatio',
                'title': '大于5%占比',
                'value': queryData.get('turnoverAbove5PctRatio', 0),
                'unit':  '%'
            },            
            {
                **data,
                'field': 'turnoverAbove5_mvChg',
                'title': '大于5%市值涨跌',
                'value': queryData.get('turnoverAbove5_mvChg', 0),
                'unit': '亿元'
            },       
        ]
    return result_data

# CloseData_HS_MARKET('20240828', 'HS_MARKET')

# tradeDate = '20240828'
# print(Daily_basic_topSum(tradeDate, 100))
